package com.todo.strategy.online.application.frontend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.enums.EnableTypeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.strategy.online.application.convert.WantSetConvert;
import com.todo.strategy.online.application.entity.bo.WantRelationBO;
import com.todo.strategy.online.application.entity.bo.WantSetBO;
import com.todo.strategy.online.application.frontend.service.WantSetAggService;
import com.todo.strategy.online.application.remote.UserInfoRemoteService;
import com.todo.strategy.online.application.service.WantRelationService;
import com.todo.strategy.online.application.service.WantSetService;
import com.todo.strategy.online.iface.request.*;
import com.todo.strategy.online.iface.response.WantSetDetailVO;
import com.todo.strategy.online.iface.response.WantSetInfoVO;
import com.todo.user.api.response.BaseUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (WantSet)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:50
 */
@Slf4j
@Service("wantSetAggService")
public class WantSetAggServiceImpl implements WantSetAggService {

    @Resource
    private UserInfoRemoteService userInfoRemoteService;
    @Resource
    private WantSetService wantSetService;
    @Resource
    private WantRelationService wantRelationService;

    @Override
    public BizResponse<Boolean> insertWantSet(InsertWantSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        WantSetBO wantSetBO = WantSetConvert.convertToWantSetBO(param);
        Boolean insertResult = wantSetService.insertWantSet(wantSetBO);
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> removeWantSetById(RemoveWantSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        List<Long> collect = param.getWantIdList().stream().map(Long::valueOf).collect(Collectors.toList());
        //根据用户信息查询是否属于当前用户，属于则删除
        List<WantSetBO> wantSetBOList = wantSetService.queryWantSetByUserId(param.get_user().getUserId());
        if (CollectionUtils.isEmpty(wantSetBOList)) {
            log.info("WantSetAggService#removeWantSetById 根据我想去列表删除数据完成，查询用户数据为空，默认全部删除 入参：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success(true);
        }
        Map<Long, WantSetBO> wantIdMap = wantSetBOList.stream().collect(Collectors.toMap(WantSetBO::getWantId, wantSetResponse -> wantSetResponse));
        List<Long> removeWantIdList = new ArrayList<>();
        for (Long wantId : collect) {
            if (wantIdMap.containsKey(wantId)) {
                removeWantIdList.add(wantId);
            }
        }
        Boolean removeResult = wantSetService.removeWantSetByIdList(removeWantIdList);
        return BizResponse.success(removeResult);
    }

    @Override
    public BizResponse<Boolean> updateWantSetById(UpdateWantSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        WantSetBO wantSetBO = wantSetService.queryWantSetById(param.getWantId());
        if (wantSetBO == null) {
            log.error("WantSetAggService#updateWantSetById 根据id更新数据完成，查询数据不存在 入参：【{}】", JSONObject.toJSONString(param));
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!param.get_user().getUserId().equals(wantSetBO.getUserId())) {
            log.error("WantSetAggService#updateWantSetById 根据id更新数据完成，查询数据不属于当前用户 入参：【{}】", JSONObject.toJSONString(param));
            throw new BizException(BizErrorCodeEnum.INSUFFICIENT_USER_PERMISSIONS);
        }
        WantSetBO request = WantSetConvert.convertToWantSetBO(param);
        Boolean updateResult = wantSetService.updateWantSet(request);
        return BizResponse.success(updateResult);
    }

    @Override
    public BizResponse<List<WantSetInfoVO>> queryWantSetByUserId(QueryWantSetByUserIdParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        BizResponse<BaseUserInfoResponse> userBizResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.getTargetUserId());
        if (userBizResponse == null || !userBizResponse.isSuccess() || userBizResponse.getData() == null) {
            log.error("WantSetAggService#queryWantSetByUserId 根据用户id查询我的想去列表完成，查询用户数据不存在 入参：【{}】", JSONObject.toJSONString(param));
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        List<WantSetBO> wantSetBOList = wantSetService.queryWantSetByUserId(param.getTargetUserId());
        if (CollectionUtils.isEmpty(wantSetBOList)) {
            log.warn("WantSetAggService#queryWantSetByUserId 根据用户id查询我的想去列表完成，查询数据为空 入参：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success();
        }
        List<WantSetInfoVO> result = new ArrayList<>();
        for (WantSetBO wantSetBO : wantSetBOList) {
            if (wantSetBO == null) {
                continue;
            }
            if (!param.get_user().getUserId().equals(param.getTargetUserId()) && EnableTypeEnum.FORBIDDEN.equals(wantSetBO.getIsPrivate())) {
                continue;
            }
            WantSetInfoVO wantSetInfoVO = WantSetConvert.buildWantSetInfoVO(userBizResponse.getData(), wantSetBO);
            wantSetInfoVO.setBelongCurrentUser(param.get_user().getUserId().equals(param.getTargetUserId()));
            result.add(wantSetInfoVO);
        }
        return BizResponse.success(result);
    }

    @Override
    public BizResponse<Boolean> insertWantSetRelation(InsertWantSetRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        WantSetBO wantSetBO = wantSetService.queryWantSetById(param.getWantId());
        if (wantSetBO == null) {
            log.error("WantSetAggService#insertWantSetRelation 新增我想去集合相信信息失败，我想去集合不存在，param：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success(false);
        }
        if (!param.get_user().getUserId().equals(wantSetBO.getUserId())) {
            log.error("WantSetAggService#insertWantSetRelation 新增我想去集合相信信息失败，用户无权限，param：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success(false);
        }
        WantRelationBO wantRelationBO = WantSetConvert.convertToWantRelationBO(param);
        Boolean insertResult = wantRelationService.insertWantRelation(wantRelationBO);
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> removeWantSetRelation(RemoveWantSetRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        WantSetBO wantSetBO = wantSetService.queryWantSetById(param.getWantId());
        if (wantSetBO == null) {
            return BizResponse.success(true);
        }
        if (!param.get_user().getUserId().equals(wantSetBO.getUserId())) {
            log.error("WantSetAggService#removeWantSetRelation 删除我想去集合关联信息失败，用户无权限，param：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success(false);
        }
        List<Long> collect = param.getWantSetRelationIdList().stream().map(Long::valueOf).collect(Collectors.toList());
        Boolean removeResult = wantRelationService.removeWantRelationByIdList(param.getWantId(), collect);
        return BizResponse.success(removeResult);
    }

    @Override
    public BizResponse<WantSetDetailVO> queryWantSetRelationByWantId(QueryWantSetRelationByWantIdParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        BizResponse<BaseUserInfoResponse> userBizResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.get_user().getUserId());
        if (userBizResponse == null || !userBizResponse.isSuccess() || userBizResponse.getData() == null) {
            return BizResponse.paramError("用户不存在");
        }
        WantSetBO wantSetBO = wantSetService.queryWantSetById(Long.valueOf(param.getWantId()));
        if (wantSetBO == null) {
            log.error("WantSetAggService#queryWantSetRelationByWantId 查询我想去集合关联信息失败，我想去集合不存在，param：【{}】", JSONObject.toJSONString(param));
            return BizResponse.paramError("数据不存在");
        }
        List<WantRelationBO> wantRelationBOList = wantRelationService.queryWantRelationBySetId(Long.valueOf(param.getWantId()));
        if (CollectionUtils.isEmpty(wantRelationBOList)) {
            WantSetDetailVO wantSetDetailVO = WantSetConvert.buildWantSetDetailVO(userBizResponse.getData(), wantSetBO);
            return BizResponse.success(wantSetDetailVO);
        }
        WantSetDetailVO wantSetDetailVO = WantSetConvert.buildWantSetDetailVO(userBizResponse.getData(), wantSetBO, wantRelationBOList);
        wantSetDetailVO.setBelongCurrentUser(param.get_user().getUserId().equals(wantSetBO.getUserId()));

        log.info("WantSetAggService#queryWantSetRelationByWantId 查询我想去集合关联信息成功，param：【{}】，结果：【{}】", JSONObject.toJSONString(param), JSONObject.toJSONString(wantSetDetailVO));
        return BizResponse.success(wantSetDetailVO);
    }
}
